<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class AddressController extends Controller
{
    /**
     * 地址
     */

    public function index()
    {
        $address = Redis::get('enum_address');
        if($address){
            return $this->setReturnJson(0,'success',json_decode($address));
        }

        $address = DB::table('dict_area')
            ->select('id','name','path','pid')
            ->get()
            ->toArray();
        $address = json_decode(json_encode($address),true);

        $result = [];
        foreach($address as $key=>$value){
            if($value['pid'] === 0){
                $result[$value['id']] = ['id'=>$value['id'],'text'=>$value['name']];
            } elseif(array_key_exists($value['pid'],$result)) {
                $result[$value['pid']]['children'][$value['id']] = ['id'=>$value['id'],'text'=>$value['name']];
            } else {
                $result[substr($value['path'],0,6)]['children'][$value['pid']]['children'][] = ['id'=>$value['id'],'text'=>$value['name']];
            }
        }
        $result = array_values($result);
        foreach($result as $key=>$value){
            $result[$key]['children'] = array_values($value['children']);
        }

//        // 仅允许北京业务
//        foreach($result as $key => $value){
//            if($value['id'] === 110000){
//                $result = [$value];
//                break;
//            }
//        }


        Redis::setex('enum_address',7200*24,json_encode($result));//一天有效

        return $this->setReturnJson(0,'success',$result);

    }

}
